﻿using System;
using System.Web.Mvc;
using Diploma.Models;
using MvcPaging;

namespace DiplomaWeb.Controllers
{
    [Authorize]
    public class MessagesController : MasterController
    {
        public MessagesController(DataManager dataManager) : base(dataManager)
        {
        }

        [HttpPost]
        public ActionResult Send(Guid roomId, string message)
        {
            CollaborationRoom room = DataManager.CollaborationRoomRepository.GetCollaborationRoom(roomId);
            if (room == null)
                throw new NotImplementedException();
            DataManager.MessagesRepository.Send(room, LoggedUser, message);
            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Delete(Guid messageId, int currentPage)
        {
            Message message = DataManager.MessagesRepository.GetMessage(messageId);
            if (message == null || message.UserId != LoggedUser.UserId)
                throw new Exception();
            CollaborationRoom room = message.CollaborationRoom;
            DataManager.MessagesRepository.Delete(message);
            return MessagesByPage(room, currentPage);
        }

        public ActionResult MessagesByPage(Guid roomId, int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value : 1;
            CollaborationRoom room = DataManager.CollaborationRoomRepository.GetCollaborationRoom(roomId);
            if (room == null)
                throw new Exception();
            return MessagesByPage(room, currentPageIndex);
        }

        private ActionResult MessagesByPage(CollaborationRoom room, int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value : 1;
            if (room == null)
                throw new Exception();
            IPagedList<Message> messages =
                DataManager.CollaborationRoomRepository.GetMessages(room).ToPagedList(currentPageIndex, 10);
            ViewData.Model = messages;
            ViewData["LoggedUser"] = LoggedUser;
            if (Request.IsAjaxRequest())
                return PartialView("MessagesListControl");
            return null;
        }
    }
}